package zh.dummy.netty.client.util;

import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.Channel;
import zh.dummy.netty.client.context.NettyManager;
import zh.dummy.netty.client.context.listener.WorkflowListener;
import zh.dummy.netty.core.exception.MessageNullException;
import zh.dummy.netty.core.protocol.NettyMessage;

public class NettyUtil {
	
	private final static Logger logger = LoggerFactory.getLogger("NettyUtil");
	
	private static NettyManager nettyManager;
	
	static{
		nettyManager = NettyManager.getInstance();
	}
	
	public static String getClientId(){
		return nettyManager.getClientId();
	}
	
	public static void setClientId(String id){
		nettyManager.setClientId(id);
	}
	
	public static Set<WorkflowListener> getListeners(){
		return nettyManager.getListeners();
	}
	
	public static void sendMessage(Map<String,Object> message){
		if(message == null || message.isEmpty()){
			throw new MessageNullException("message cannot be null");
		}
		doSend(message);
	}
	
	private static void doSend(Map<String, Object> message) {
		Channel channel  = nettyManager.getChannel();
		if(channel == null){
			if(logger.isInfoEnabled()){
				logger.info("channel cannot be null");
			}
			return;
		}
		if(channel.isActive()){
			if(logger.isInfoEnabled()){
				logger.info("send message : {}",new Object[]{message.toString()});
			}
			NettyMessage nettyMessage = NettyMessageBuilder.buildWorkflowMessage(message);
			channel.writeAndFlush(nettyMessage);
		}else{
			if(logger.isInfoEnabled()){
				logger.info("channel is not actived");
			}
		}
	}
}